#!/bin/bash

MAKE="make -j32"
outDirectory=$(pwd)/out
aarch64buildlog="$outDirectory/aarch64build.log"

setarm64ENV() {
    export AS=${OHOS_SDK}/native/llvm/bin/llvm-as
    export CC=${OHOS_SDK}/native/llvm/bin/aarch64-linux-ohos-clang
    export CXX=${OHOS_SDK}/native/llvm/bin/aarch64-linux-ohos-clang++
    # export LD=${OHOS_SDK}/native/llvm/bin/ld.lld
    export LD=${OHOS_SDK}/native/llvm/bin/aarch64-linux-ohos-clang++
    export STRIP=${OHOS_SDK}/native/llvm/bin/llvm-strip
    export RANLIB=${OHOS_SDK}/native/llvm/bin/llvm-ranlib
    export OBJDUMP=${OHOS_SDK}/native/llvm/bin/llvm-objdump
    export OBJCOPY=${OHOS_SDK}/native/llvm/bin/llvm-objcopy
    export NM=${OHOS_SDK}/native/llvm/bin/llvm-nm
    export AR=${OHOS_SDK}/native/llvm/bin/llvm-ar
    export CFLAGS="-DOHOS_NDK -fPIC -D__MUSL__=1"
    export CXXFLAGS="-DOHOS_NDK -fPIC -D__MUSL__=1"
    export LDFLAGS=""
}

unsetarm64ENV() {
    unset AS CC CXX LD STRIP RANLIB OBJDUMP OBJCOPY NM AR CFLAGS CXXFLAGS LDFLAGS
}

build() {

    if [ ! -d "$outDirectory" ]; then
        mkdir -p "$outDirectory"
    fi

    setarm64ENV

    TARGET_ABI=aarch64-linux-ohos
    OHOS_SYSROOT=${OHOS_SDK}/native/sysroot
    STDCPP_TC_VER=${OHOS_SYSROOT}/usr

    STDCPP_CFLAGS="-I${STDCPP_TC_VER}/include"
    STDCPP_LDFLAGS="-L${STDCPP_TC_VER}/lib/${TARGET_ABI}/"

    export CFLAGS="${CFLAGS} --sysroot=${OHOS_SYSROOT}"
    export LDFLAGS="${LDFLAGS} --sysroot=${OHOS_SYSROOT}"
    export CXXFLAGS="${CXXFLAGS} --sysroot=${OHOS_SYSROOT} -fexceptions -frtti ${STDCPP_CFLAGS}"
    export CPPFLAGS="${CFLAGS} -fexceptions -frtti"

    # 链接库
    export LIBS="-lohaudio -lohcamera -limage_receiver -lnative_image -lohimage \
        -lnative_buffer -lhilog_ndk.z -lnative_media_codecbase \
        -lnative_media_core -lnative_media_vdec -lc++_shared \
        -lnative_window -lEGL -lGLESv3 -lnative_media_venc"

    ./configure --prefix="$outDirectory/arm64-v8a" --enable-shared --disable-libwebrtc --host=aarch64-linux
    if [ $? -ne 0 ]; then
        echo "Error: Configuration failed for arm64-v8a"
        unsetarm64ENV
        exit 1
    fi

    ${MAKE} dep
    if [ $? -ne 0 ]; then
        echo "Error: dep failed for arm64-v8a."
        unsetarm64ENV
        exit 1
    fi

    ${MAKE} VERBOSE=1 > $aarch64buildlog 2>&1
    if [ $? -ne 0 ]; then
        echo "Error: MAKE failed for arm64-v8a. Check the log file: $aarch64buildlog"
        unsetarm64ENV
        exit 1
    fi

    ${MAKE} install

    unsetarm64ENV
}

clear() {
    echo start clear
    $MAKE clean
    $MAKE distclean
    # rm -rf $outDirectory
}

main() {
    if [ $# -eq 0 ]; then
        # No arguments, default to build
        build
    elif [ "$1" == "-c" ]; then
        # If argument is -c, call the clear function
        clear
    else
        echo "Usage: $0 [-c]"
        echo "  -c    Clean the build"
        exit 1
    fi
}

main $*